package com.mingtu.guards.fragment;

import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.decoration.BottomSpaceItemDecoration;
import com.mingtu.common.decoration.TopSpaceItemDecoration;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.view.EmptyDataLayout;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.guards.R;
import com.mingtu.guards.activity.FireTaskActivity;
import com.mingtu.guards.activity.TaskDetails1Activity;
import com.mingtu.guards.adapter.JobSupervisionAdapter;
import com.mingtu.guards.bean.SuperJobListBean;
import com.mingtu.guards.utils.MyConstant;
import com.mingtu.guards.utils.MySPTools;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.mingtu.guards.utils.MyConstant.animationType;
import static com.mingtu.guards.utils.MyConstant.isFirstOnly;
import static com.mingtu.guards.utils.MyConstant.isOpenLoadAnimation;

public class JobTodatyFragment extends BaseFragment implements LazyFragmentPagerAdapter.Laziable {


    @BindView(R.id.recycler)
    RecyclerView recycler;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;

    private int currentPage = 1;
    private boolean isLoadMore = true;
    private JobSupervisionAdapter jobSupervisionAdapter;
    private String type = null;

    public static JobTodatyFragment getInstance() {
        JobTodatyFragment fragment = new JobTodatyFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_job_today;
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initView(View view) {
        LinearLayoutManager manager1 = new LinearLayoutManager(context);
        recycler.setLayoutManager(manager1);
        recycler.addItemDecoration(new TopSpaceItemDecoration());
        recycler.addItemDecoration(new BottomSpaceItemDecoration());

        jobSupervisionAdapter = new JobSupervisionAdapter(context);
        if (isOpenLoadAnimation) {
           jobSupervisionAdapter.isFirstOnly(isFirstOnly);
           jobSupervisionAdapter.openLoadAnimation(animationType);
        }

        jobSupervisionAdapter.setEmptyView(new EmptyDataLayout(context));

        recycler.setAdapter(jobSupervisionAdapter);
        jobSupervisionAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                SuperJobListBean.PageBean.ListBean listBean = jobSupervisionAdapter.getData().get(position);
                String taskId = listBean.getId() + "";
                String type = listBean.getType();

                if (type.indexOf(MyConstant.TASK_TYPE_TRACK) != -1) {
                    ToastUtils.showLong("巡护任务没有详情哦~");
                } else if (type.indexOf(MyConstant.TASK_TYPE_SEND) != -1) {
                    Bundle bundle = new Bundle();
                    bundle.putString("taskId", taskId);
                    bundle.putString("taskType", type);
                    IntentUtils.getInstance().readyGo(getActivity(), TaskDetails1Activity.class, bundle);
                } else if (type.indexOf(MyConstant.TASK_TYPE_SEND) != -1) {
                    Bundle bundle4 = new Bundle();
                    bundle4.putString("taskId", taskId + "");
                    bundle4.putString("taskType", type);
                    IntentUtils.getInstance().readyGo(getActivity(), FireTaskActivity.class, bundle4);
                }
            }
        });
    }

    @Override
    protected void getData() {
        initListener();
        getSuperJobList(1);
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (requestCode == 100) {
//            if (resultCode == 200) {
//                getSuperJobList(1);
//            }
//        }
//    }

    private void initListener() {
        initPullRefresh();//刷新
        initLoadMoreListener();//加载更多
    }

    private void initPullRefresh() {
        srlUp.setPrimaryColorsId(R.color.colorPrimary, android.R.color.white);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
                currentPage = 1;
                getSuperJobList(1);
            }
        });
    }

    private void initLoadMoreListener() {
        srlUp.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isLoadMore) {
                    currentPage = MyUtills.loadPage(jobSupervisionAdapter.getData(), Constant.PAGE_SIZE);
                    getSuperJobList(currentPage);
                }
                srlUp.finishLoadMore(Constant.LOADMORE_TIME);
            }
        });

    }

    /**
     * 今日到期的督办工作列表
     */
    private void getSuperJobList(int pageNum) {
        if (pageNum == 1) {
            currentPage = 1;
        }
        String beginTime = SPStaticUtils.getString(MySPTools.superJobFliteBeginTime);
        String endTime = SPStaticUtils.getString(MySPTools.superJobFliteEndTime);
        String type = SPStaticUtils.getString(MySPTools.superJobType);

        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("curPage", pageNum);
        hashMap.put("pageSize", Constant.PAGE_SIZE);
        hashMap.put("beginTime", beginTime);
        hashMap.put("endTime", endTime);
        hashMap.put("type", type);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_SUPER_TODAY_LIST)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {

                            try {
                                Gson gson = GsonFactory.getSingletonGson();
                                SuperJobListBean superJobListBean = new SuperJobListBean();
                                superJobListBean = gson.fromJson(result, SuperJobListBean.class);
                                List<SuperJobListBean.PageBean.ListBean> dataBeans = superJobListBean.getPage().getList();

                                try {
                                    if (dataBeans != null) {
                                        isLoadMore = dataBeans.size() > 0 && dataBeans.size() % Constant.PAGE_SIZE == 0 ? true : false;
                                        //当是第一页的时候先清空数组，防止下拉操作的时候加载重复数据
                                        if (currentPage == 1) {
                                            jobSupervisionAdapter.replaceData(dataBeans);
                                        } else {
                                            jobSupervisionAdapter.addData(dataBeans);
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }


                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                                isLoadMore = false;
                                ToastUtils.showLong(getResources().getString(com.mingtu.center.R.string.text_json_error));
                            }
                        }
                    }
                });
    }

    /**
     * 筛选数据
     */
    public void filtJob() {
        getSuperJobList(1);
    }

    /**
     * 重置数据
     */
    public void resetData() {
        type = null;
        getSuperJobList(1);
    }

}